package icom.acm.admin.manager;

import icom.acm.admin.been.AFunction;
import icom.acm.util.DBConnect;

import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

/**
 * 连接数据对功能节点进行增删改查
 * @author shench
 * @since 2012-4-27
 */
public class AFunctionMgr {
	/**
	 * 找到所有功能节点通过 ID 和 顺序编号 排序
	 *
	 */
	public List<AFunction> findAllByID_OrderId(){
		final List<AFunction> list = new ArrayList<AFunction>();
		final DBConnect db = new DBConnect();
		final String sql = "SELECT WAF.F_ID AS F_ID, WAF.F_PID AS F_PID, " +
				"WAF.F_NAME AS F_NAME, WAF.F_FRAME AS F_FRAME, " +
				"WAF.F_URL AS F_URL, WAF.F_ORDERID AS F_ORDERID, " +
				"WAFL.FL_LEVEL AS F_LEVEL FROM " +
				"WB_A_FUNCTION WAF, WB_A_FUNCTION_LEVEL WAFL WHERE " +
				"WAFL.FL_ID=WAF.F_ID;";
		db.prepareStatement(sql);
		
		db.excuteQuery();
		
		try {
			while (db.next()){
				final AFunction func = new AFunction();
				func.setF_ID(db.getInt("F_ID"));
				func.setF_PID(db.getInt("F_PID"));
				func.setF_NAME(db.getString("F_NAME"));
				func.setF_FRAME(db.getString("F_FRAME"));
				func.setF_URL(db.getString("F_URL"));
				func.setF_ORDERID(db.getInt("F_ORDERID"));
				func.setF_LEVEL(db.getInt("F_LEVEL"));
				list.add(func);
			}
		}catch (final Exception ex){ex.printStackTrace();}finally{db.close();}
		
		return list;
	}
	/**
	 * 创建一个功能节点到数据库
	 * @param func
	 */
	public void save(final AFunction func){
		final DBConnect db = new DBConnect();
		final String sql = "INSERT INTO WB_A_FUNCTION" +
				"(F_PID, F_NAME, F_FRAME, F_URL, F_ORDERID) VALUES" +
				"("+ func.getF_PID() + ", '" + func.getF_NAME() + "', '" + 
					func.getF_FRAME() + "', '" + func.getF_URL() + "', " + 
					func.getF_ORDERID() + ")";
		db.prepareStatement(sql);
		try {
			db.excute();
		} catch (MySQLIntegrityConstraintViolationException e) {
			e.printStackTrace();
		}
		db.close();		
	}
	
	public void update(final AFunction func){
		final DBConnect db = new DBConnect();
		final String sql = "UPDATE WB_A_FUNCTION SET " +
				"F_PID="+func.getF_PID()+", " +
				"F_NAME='"+func.getF_NAME()+"', " +
				"F_FRAME='"+func.getF_FRAME()+"', " +
				"F_URL='"+func.getF_URL()+"' WHERE F_ID=" + func.getF_ID();				
		db.prepareStatement(sql);
		db.excuteUpdate();
		db.close();		
	}
}
